import sys,os,time
from simpledcpp.core.base import DCPPPart, start_new_thread, DCPPEvent

class UploadConnection(DCPPPart):
	def __init__(self, parent, condata):
		DCPPPart.__init__(self, parent)
		self.Events.Subscribe("DESTROY_CONNECTION", self._destroy)
		self._stopped = 0
		self.direction = "Upload"
		self._socket, self._type, self._name, self._fr, self._to, self._n = condata
		self._speed = 0

	def _destroy(self, Event):
		if int(Event.userdata[0]) == int(self.cid):
			self.stop()
	def _preprocessing(self):
		try:
			self._processing()
		except:
			print sys.exc_info()
		self.stop()
	def _processing(self):
		real_file_name = None
		if self._name.startswith("TTH/"):
			finfo = self.filelist.getInfoByTTH(self._name.split('/')[1])
			if finfo == None:
				self._socket.Send("$Error File Not Found|")
				self.stop()
				return
			self._filesize = finfo[1]
			self._filename = self.filelist.getRealName(finfo[0])
		elif self._name == 'files.xml.bz2':
			filelist = os.path.join(os.getenv("HOME"),'.simpledcpp/files.xml.bz2')
			if os.path.isfile(filelist):
				self._filename = filelist
				self._filesize = os.path.getsize(filelist)
			else:
				self._socket.Send("$Error File Not Found|")
				self.stop()
				return
		else:
			self._filename = self.filelist.getRealName(self._name)
		if self._filename == None:
			self.stop()
		if self._to == '-1':
			self._to = self._filesize
		self._socket.Send("$ADCSND %s %s %s %s|"%(self._type,self._name, self._fr, self._to))
		if not self._socket.ok():
			self.stop()
			return
		self._sendFile()
		self.stop()

	def _sendFile(self):
		self._fr = int(self._fr)
		self._to = int(self._to)
		filed = open(self._filename)
		filed.seek(self._fr)
		count = int(self._to/1024)
		read_time = time.time()
		read_send = 0
		self._speed = 0
		self._progress = 0
		for i in range(0, count):
			buf = filed.read(1024)
			self._socket.Send(buf, enc = False)
			read_send = read_send + len(buf)
			self._progress = self._progress + len(buf)
			if time.time() - read_time >= 1:
				self._speed = read_send
				read_send = 0
				read_time = time.time()
				self.Event(DCPPEvent("ON_CONNECTION_UPDATE",(self.cid,self._speed,self._progress,self._filename,self._to,"",self._n)))
			elif time.time() - read_time <= 1 and read_send > int(self.settings.get("upload_speed")):
				try:
					time.sleep(read_time + 1 - time.time())
				except:
					pass
			if not self._socket.ok():
				self.stop()
				filed.close()
				return
		self.Event(DCPPEvent("ON_CONNECTION_UPDATE",(self.cid,self._speed,self._progress,self._filename,self._to,"",self._n)))
		tail = self._to - count * 1024
		buf = filed.read(tail)
		self._socket.Send(buf, enc = False)
		self._progress = self._progress + len(buf)
		time.sleep(2)
		filed.close()
		
	def start(self):
		self._thread = start_new_thread(self._preprocessing)

	def stop(self):
                self.Events.Unsubscribe("DESTROY_CONNECTION", self._destroy)

		if self._stopped:
			return
		self._stopped = 1
		try:
			self._thread.kill()
		except:
		#	print sys.exc_info()
			pass
		self._socket.Close()
		self.Event(DCPPEvent("ON_DESTROY_CONNECTION",(self,)))
#		print "Destroyed"
